package com.team1.system.stats.controller;

import com.team1.system.librarystock.domain.LibraryStock;
import com.team1.system.librarystock.service.ILibraryStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class StatsStockController {
    @Autowired
    private ILibraryStockService libraryStockService;
//统计每个图书库存量
    public Map bookInventory(){
        LibraryStock libraryStock = new LibraryStock();
        List<LibraryStock> list = libraryStockService.selectLibraryStockList(libraryStock);
        Map<Long,Long> bookStockMap = new HashMap<>();
        for (LibraryStock l : list) {
            long bookId = l.getBookId();
            long bookStock = l.getBookStock() ;
            if (bookStockMap.containsKey(bookId)) {
                bookStockMap.put(bookId,bookStockMap.get(bookId) +  bookStock);
            } else {
                bookStockMap.put(bookId,bookStock);
            }
        }
        return bookStockMap;
    }
//获取指定图书id的库存量
    public Long getBookInventoryById(Long bId){
        Map<Long,Long> bookStockMap = bookInventory();
        Long bookStock = bookStockMap.get(bId);
        return bookStock;
    }

//统计库存前10的图书id和库存量(从小到大排序)
public List<Map.Entry<Long,Long>> bookInventorySorter(){
    Map<Long,Long> bookStockMap = bookInventory();
    // 对库存数量进行从小到大排序，选取前十个元素
    List<Map.Entry<Long,Long>> topTenBooks = bookStockMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .limit(10)
            .collect(Collectors.toList());
    // 返回结果
    return topTenBooks;
    }
}
